#include "settingsdialog.h"
#include "configmanager.h"    // 依赖 core 模块的配置管理
#include "skinmanager.h"      // 依赖 UI 模块的皮肤管理

#include <QApplication>
#include <QDebug>

SettingsDialog::SettingsDialog(QWidget *parent)
    : QDialog(parent)
{
	initUI();
	loadConfigToUI();
}

void SettingsDialog::saveInputMethodConfig() {
	ConfigManager* config = ConfigManager::getInstance();
    InputMethodConfig::Data imConfig = config->getInputMethodConfig();

    imConfig.doublePinyinScheme = m_doublePinyinCombo->currentText();
    imConfig.candidateCount = m_candidateCountSpin->value();
    imConfig.fuzzyPinyin = m_fuzzyPinyinCheck->isChecked();
    imConfig.autoAddWord = m_autoAddWordCheck->isChecked();
    imConfig.autoAddThreshold = m_autoAddThresholdSpin->value();

    config->setInputMethodConfig(imConfig);
    qDebug() << "[Settings] 输入法配置保存完成";
}

void SettingsDialog::saveGeneralConfig()
{
	ConfigManager* config = ConfigManager::getInstance();
    GeneralConfig::Data generalConfig = config->getGeneralConfig();

    generalConfig.language = m_languageCombo->currentText().startsWith("zh_CN") ? "zh_CN" : "en_US";
    generalConfig.autoStart = m_autoStartCheck->isChecked();
    generalConfig.showTrayIcon = m_showTrayCheck->isChecked();

    config->setGeneralConfig(generalConfig);
    qDebug() << "[Settings] 通用配置保存完成";
}

void SettingsDialog::saveShortcutConfig()
{
	ConfigManager* config = ConfigManager::getInstance();
    ShortcutConfig::Data shortcutConfig = config->getShortcutConfig();

    shortcutConfig.switchLanguage = m_switchLangEdit->keySequence().toString();
    shortcutConfig.switchSimplifiedTraditional = m_switchSimpTradEdit->keySequence().toString();
    shortcutConfig.showNumpad = m_showNumpadEdit->keySequence().toString();

    config->setShortcutConfig(shortcutConfig);
    qDebug() << "[Settings] 快捷键配置保存完成";
}

void SettingsDialog::saveAppearanceConfig()
{
	ConfigManager* config = ConfigManager::getInstance();
    AppearanceConfig::Data appearanceConfig = config->getAppearanceConfig();

    // 提取皮肤名称（如 "default（默认）" → "default"）
    QString skinText = m_skinCombo->currentText();
    appearanceConfig.skin = skinText.left(skinText.indexOf("（"));
    appearanceConfig.fontSize = m_fontSizeSpin->value();
    appearanceConfig.windowTransparency = m_transparencySpin->value();

    config->setAppearanceConfig(appearanceConfig);
    // 实时切换皮肤
    SkinManager::instance()->loadSkin(appearanceConfig.skin);
    qDebug() << "[Settings] 外观配置保存完成";
}

void SettingsDialog::restoreDefaultConfig()
{
	ConfigManager* config = ConfigManager::getInstance();
    config->restoreDefaults();  // 调用核心模块的默认配置恢复
    loadConfigToUI();           // 重新加载UI
    emit configChanged();
    qDebug() << "[Settings] 所有配置已恢复默认";
}

void SettingsDialog::initUI()
{
	// base setting
	setWindowTitle("输入法设置");
	setFixedSize(500, 400);
    setStyleSheet(R"(
        SettingsDialog {
            background-color: white;
        }
        QTabWidget::pane {
            border-top: 2px solid #E6E6E6;
            margin-top: 5px;
        }
        QTabBar::tab {
            width: 100px;
            height: 35px;
            font-size: 13px;
            margin-right: 2px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            background-color: #F5F5F5;
        }
        QTabBar::tab:selected {
            background-color: white;
            border-top: 2px solid #1890FF;
        }
        QFormLayout {
            margin: 20px;
            spacing: 15px;
        }
        QLabel {
            font-size: 12px;
            color: #666666;
        }
        QSpinBox, QComboBox, QKeySequenceEdit {
            height: 30px;
            font-size: 12px;
            border: 1px solid #E6E6E6;
            border-radius: 4px;
        }
        QPushButton {
            height: 35px;
            font-size: 13px;
            border-radius: 4px;
            border: none;
        }
        QPushButton#SaveBtn {
            background-color: #1890FF;
            color: white;
        }
        QPushButton#SaveBtn:hover {
            background-color: #096DD9;
        }
        QPushButton#DefaultBtn {
            background-color: #F5F5F5;
            color: #333333;
        }
        QPushButton#DefaultBtn:hover {
            background-color: #E6E6E6;
        }
    )");

	// label + btn
	QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 20);
    mainLayout->setSpacing(10);

	// setting cover label
	QTabWidget* tabWidget = new QTabWidget();
    initInputMethodTab(tabWidget);
    initGeneralTab(tabWidget);
    initShortcutTab(tabWidget);
    initAppearanceTab(tabWidget);
    mainLayout->addWidget(tabWidget);

	// btn save + default
	QHBoxLayout* btnLayout = new QHBoxLayout();
    btnLayout->setContentsMargins(20, 0, 20, 0);
    btnLayout->setSpacing(10);

    QPushButton* saveBtn = new QPushButton("保存所有配置");
    saveBtn->setObjectName("SaveBtn");
	connect(saveBtn, &QPushButton::clicked, this, [this]() {
		saveInputMethodConfig();
        saveGeneralConfig();
        saveShortcutConfig();
        saveAppearanceConfig();
        emit configChanged();
        this->close();
	});
	auto* defaultBtn = new QPushButton("恢复默认配置");
    defaultBtn->setObjectName("DefaultBtn");
    connect(defaultBtn, &QPushButton::clicked, this, &SettingsDialog::restoreDefaultConfig);

    btnLayout->addStretch();
    btnLayout->addWidget(defaultBtn);
    btnLayout->addWidget(saveBtn);
    mainLayout->addLayout(btnLayout);
}

void SettingsDialog::initInputMethodTab(QTabWidget *tabWidget)
{
	auto* imTab = new QWidget();
	QFormLayout* imLayout = new QFormLayout(imTab);

	// 双拼
	m_doublePinyinCombo = new QComboBox();
    m_doublePinyinCombo->addItems({"Sogou", "Microsoft"});
    imLayout->addRow("双拼方案：", m_doublePinyinCombo);
	// candidate
	m_candidateCountSpin = new QSpinBox();
    m_candidateCountSpin->setRange(3, 9);
    imLayout->addRow("候选词数量：", m_candidateCountSpin);
	// 模糊音
	m_fuzzyPinyinCheck = new QCheckBox();
    imLayout->addRow("启用模糊音：", m_fuzzyPinyinCheck);
	// auto 造词
	m_autoAddWordCheck = new QCheckBox();
    imLayout->addRow("启用自动造词：", m_autoAddWordCheck);
	// auto factor
	m_autoAddThresholdSpin = new QSpinBox();
    m_autoAddThresholdSpin->setRange(2, 5);
    imLayout->addRow("自动造词阈值：", m_autoAddThresholdSpin);

    tabWidget->addTab(imTab, "输入法设置");
}

void SettingsDialog::initGeneralTab(QTabWidget *tabWidget)
{
	auto* generalTab = new QWidget();
	QFormLayout* generalLayout = new QFormLayout(generalTab);

	// 语言选择
    m_languageCombo = new QComboBox();
    m_languageCombo->addItems({"zh_CN（中文）", "en_US（英文）"});
    generalLayout->addRow("界面语言：", m_languageCombo);
    // 开机自启
    m_autoStartCheck = new QCheckBox();
    generalLayout->addRow("开机自启：", m_autoStartCheck);
    // 显示托盘图标
    m_showTrayCheck = new QCheckBox();
    generalLayout->addRow("显示托盘图标：", m_showTrayCheck);

    tabWidget->addTab(generalTab, "通用设置");
}

void SettingsDialog::initShortcutTab(QTabWidget *tabWidget)
{
	QWidget* shortcutTab = new QWidget();
    QFormLayout* shortcutLayout = new QFormLayout(shortcutTab);

    // 中英文切换
    m_switchLangEdit = new QKeySequenceEdit();
    shortcutLayout->addRow("中英文切换：", m_switchLangEdit);
    // 简繁切换
    m_switchSimpTradEdit = new QKeySequenceEdit();
    shortcutLayout->addRow("简繁切换：", m_switchSimpTradEdit);
    // 显示数字面板
    m_showNumpadEdit = new QKeySequenceEdit();
    shortcutLayout->addRow("显示数字面板：", m_showNumpadEdit);

    tabWidget->addTab(shortcutTab, "快捷键设置");
}

void SettingsDialog::initAppearanceTab(QTabWidget *tabWidget)
{
	QWidget* appearanceTab = new QWidget();
    QFormLayout* appearanceLayout = new QFormLayout(appearanceTab);

    // 皮肤选择
    m_skinCombo = new QComboBox();
    m_skinCombo->addItems({"default（默认）", "dark（深色）", "simple（简约）"});
    appearanceLayout->addRow("皮肤主题：", m_skinCombo);
    // 字体大小（10-20号）
    m_fontSizeSpin = new QSpinBox();
    m_fontSizeSpin->setRange(10, 20);
    appearanceLayout->addRow("字体大小：", m_fontSizeSpin);
    // 窗口透明度（50-100%）
    m_transparencySpin = new QSpinBox();
    m_transparencySpin->setRange(50, 100);
    m_transparencySpin->setSuffix("%");
    appearanceLayout->addRow("窗口透明度：", m_transparencySpin);

    tabWidget->addTab(appearanceTab, "外观设置");
}

void SettingsDialog::loadConfigToUI()
{
	// config 里面去获取
	ConfigManager* config = ConfigManager::getInstance();
	// load input 
	InputMethodConfig::Data imConfig = config->getInputMethodConfig();
    m_doublePinyinCombo->setCurrentText(imConfig.doublePinyinScheme);
    m_candidateCountSpin->setValue(imConfig.candidateCount);
    m_fuzzyPinyinCheck->setChecked(imConfig.fuzzyPinyin);
    m_autoAddWordCheck->setChecked(imConfig.autoAddWord);
    m_autoAddThresholdSpin->setValue(imConfig.autoAddThreshold);
	// load general
	GeneralConfig::Data generalConfig = config->getGeneralConfig();
    m_languageCombo->setCurrentText(generalConfig.language == "zh_CN" ? "zh_CN（中文）" : "en_US（英文）");
    m_autoStartCheck->setChecked(generalConfig.autoStart);
    m_showTrayCheck->setChecked(generalConfig.showTrayIcon);
	// load shortcut
	ShortcutConfig::Data shortcutConfig = config->getShortcutConfig();
    m_switchLangEdit->setKeySequence(QKeySequence(shortcutConfig.switchLanguage));
    m_switchSimpTradEdit->setKeySequence(QKeySequence(shortcutConfig.switchSimplifiedTraditional));
    m_showNumpadEdit->setKeySequence(QKeySequence(shortcutConfig.showNumpad));
	// appearance
	AppearanceConfig::Data appearanceConfig = config->getAppearanceConfig();
    m_skinCombo->setCurrentText(QString("%1（%2）").arg(appearanceConfig.skin)
                                .arg(appearanceConfig.skin == "default" ? "默认" : 
                                     appearanceConfig.skin == "dark" ? "深色" : "简约"));
    m_fontSizeSpin->setValue(appearanceConfig.fontSize);
    m_transparencySpin->setValue(appearanceConfig.windowTransparency);
}
